package com.book.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.common.annotation.Log;
import com.book.common.annotation.Login;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.AddressUtil;
import com.book.common.utils.BrowserAndOsUtil;
import com.book.common.utils.IPUtil;
import com.book.system.entity.LoginLog;
import com.book.system.mapper.LoginLogMapper;
import com.book.system.service.LoginLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: 黄海峰
 * @Description:  20155933
 */

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    @Autowired
    LoginLogMapper loginLogMapper;


    @Override
    public List<LoginLog> findAllLogs(LoginLog log) {
        QueryWrapper<LoginLog> logQueryWrapper = new QueryWrapper<>();
        return this.baseMapper.selectList(logQueryWrapper);
    }

    @Override
    public IPage<LoginLog> getLogByPage(QueryRequest request, LoginLog log) {
        QueryWrapper<LoginLog> logQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(log.getUsername())) {
            logQueryWrapper.like("username", log.getUsername());
        }
        if (StringUtils.isNotEmpty(log.getLocation())) {
            logQueryWrapper.like("location", log.getLocation());
        }
        Page<LoginLog> logPage = new Page<>(request.getPageNum(), request.getPageSize());
        return this.page(logPage, logQueryWrapper);
    }

    @Override
    public void deleteLogs(String[] logIds) {
        List<String> list = Arrays.asList(logIds);
        this.removeByIds(list);
    }

    @Override
    public void saveLogin(LoginLog loginLog, HttpServletRequest request) {
        loginLog.setLogintime(new Date())
                .setLocation(AddressUtil.getCityInfo(IPUtil.getIpAddr(request)))
                .setSystem(BrowserAndOsUtil.getOs())
                .setBrowser(BrowserAndOsUtil.getBrowser(request));
        save(loginLog);
    }
}